import { AnimationMixer } from "three"

// 动画
export default class ModelAnimation {
  constructor(model) {
    this.mixer = new AnimationMixer(model) //动画混合器对象实例
    this.animations = model.animations //存储模型的所有动画
    this.actionObj = {} //存储所有动作
    this.currentAction = null //当前播放的动画
    this.prevAction = null //上一次播放的动画
  }
  start(name){
    this.actionInit(name)
    // this.currentAction = this.actionObj['walk']
    // this.currentAction.play()
  }
  // 动画取出动作
  actionInit(name){
    this.animations.forEach(clip => {
      const action = this.mixer.clipAction(clip)
      this.actionObj[clip.name] = action
    });
    console.log(this.actionObj);
    this.currentAction = this.actionObj[name]
    this.currentAction.play()
  }

  // 更新动作
  updateAction(name, duration=0.2){
    this.prevAction = this.currentAction
    this.currentAction = this.actionObj[name]
    if(this.prevAction != this.currentAction){
      this.prevAction.fadeOut(duration)
      this.currentAction.reset().fadeIn(duration).play()
    }
  }

  update(dt){
    this.mixer.update(dt)
  }

  //获取动作持续时间
  getAnimationDuration(name){
    const action = this.actionObj[name]
    const clip = action.getClip()
    if (action && clip) {
      return clip.duration
    }
    return 0
  }
}